import L from 'leaflet';

// 工具函数：递归收集所有实际 Polygon 子图层
export function collectAllPolygons(layer: L.Layer): L.Polygon[] {
  const result: L.Polygon[] = [];
  if ((layer as any).getLatLngs && typeof (layer as any).getLatLngs === 'function') {
    result.push(layer as L.Polygon);
  }
  if ((layer as any).eachLayer) {
    (layer as any).eachLayer((subLayer: any) => {
      result.push(...collectAllPolygons(subLayer));
    });
  }
  return result;
}

// 工具函数：递归拍平 L.LatLng[] | L.LatLng[][] | L.LatLng[][][] 为 L.LatLng[]
export function flattenLatLngs(latlngs: any): L.LatLng[] {
  if (!Array.isArray(latlngs)) return [];
  const result: L.LatLng[] = [];
  (function flat(arr: any[]) {
    for (const item of arr) {
      if (Array.isArray(item)) {
        flat(item);
      } else if (item && typeof item.lat === 'number' && typeof item.lng === 'number') {
        result.push(item);
      }
    }
  })(latlngs);
  return result;
}
